package com.ks.winterwarmimage;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.Switch;
import android.widget.TextView;

import com.ks.winterwarmimage.adapter.WiFiAdapter;
import com.ks.winterwarmimage.database.DatabaseManager;
import com.ks.winterwarmimage.esptouch.EspTouchManage;
import com.ks.winterwarmimage.mqtt.MqttMag;
import com.ks.winterwarmimage.utils.BasicsUtil;
import com.ks.winterwarmimage.utils.CmdDataPacket;
import com.ks.winterwarmimage.utils.Constants;
import com.ks.winterwarmimage.wifi.WiFiTools;

import java.util.List;
/**
 * 设备注册界面
 */
public class DevRegisterActivity extends BaseActivity implements View.OnClickListener{
    private static final String base_topic="WinterWarmImage/dev/";
    private static final String TAG = DevRegisterActivity.class.getSimpleName();
    private TextView textTitle, textWifiSSID,textWifiBSSID,textTouchState,textDenNameCount;
    private TextView textConfigNetworkTitle,textConfigNetworkTip;
    private EditText textWifiPassword,textDevName;
    private Switch switchBind;
    private TextView btnConfigure;
    private WiFiTools wifiTools=null;
    //private PopupMenu popupMenu=null;
    private Bundle bundle=null;
    private Intent resultData=null;
    private EspTouchManage espTouchManage=null;
    private String accountID;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dev_register);
        textTitle = findViewById(R.id.text_title);
        textTouchState=findViewById(R.id.text_touch_state);
        textWifiSSID = findViewById(R.id.text_wifi_ssid);
        textWifiBSSID=findViewById(R.id.text_wifi_bssid);
        textWifiPassword = findViewById(R.id.text_wifi_password);
        setEditTextDrawableRight(null, textWifiPassword, false);   //设置输入框不显示明文（密码不显示）
        textDevName = findViewById(R.id.text_dev_name);
        textDenNameCount=findViewById(R.id.text_name_count);
        textConfigNetworkTitle=findViewById(R.id.text_config_network_title);
        textConfigNetworkTip=findViewById(R.id.text_config_network_tip);
        btnConfigure=findViewById(R.id.btn_start_configure);
        switchBind=findViewById(R.id.switch_bind);
        findViewById(R.id.img_return).setOnClickListener(this);
        findViewById(R.id.linrar_wifi_ssid).setOnClickListener(this);
        findViewById(R.id.img_wifi_password).setOnClickListener(this);
        btnConfigure.setOnClickListener(this);
        textDevName.addTextChangedListener(devNameChangedListener);
        accountID= DatabaseManager.getCurrentAccount();  //读取当前账户ID
        bundle=getIntent().getExtras();           //获取上个活动发送过来的数据
        if(bundle!=null && bundle.containsKey(Constants.KEY_MAC_ID)){  //判断是否是扫描WiFi界面启动的
            findViewById(R.id.linear_bind).setVisibility(View.GONE);  //由于是变更网络，所以默认都是仅配网
            switchBind.setChecked(false);
            textTitle.setText(R.string.title_network_reset);
            if(bundle.containsKey(Constants.KEY_DEV_NAME)) {
                textDevName.setText(bundle.getString(Constants.KEY_DEV_NAME));
                textDevName.setEnabled(false);
            }
        }else{
            textTitle.setText(R.string.title_reg_dev);
            textDevName.setEnabled(true);
        }
        if(switchBind.isChecked()){
            textConfigNetworkTitle.setText(R.string.config_network_and_account_dev_name);
            textConfigNetworkTip.setText(R.string.bind_account_dev_name_tip);
        }else{
            textConfigNetworkTitle.setText(R.string.only_config_network);
            textConfigNetworkTip.setText(R.string.bind_tip);
        }
        wifiTools =new WiFiTools(this);    //初始化WiFi工具类
        WiFiTools.WiFi wifi = wifiTools.getConnectedWifi(); //获取当前连接的WiFi信息
        if (wifi != null && wifi.ssid != null && wifi.ssid.length() > 0) {
            textWifiSSID.setText(wifi.ssid);
            textWifiBSSID.setText(wifi.bssid.toUpperCase());
        }
        wifiTools.regReceiver();
        espTouchManage=new EspTouchManage(this,true);
        espTouchManage.startSync();
        bindMqttService();
    }
    @Override
    protected void onDestroy() {
        unMqttBroadcastReceiver();
        espTouchManage.release();  //释放资源
        wifiTools.removeScanListener();
        wifiTools.removeConnectListener();
        wifiTools.unRegReceiver(); //注销扫描广播
        super.onDestroy();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            Log.e(TAG,"按下Back或Home键退出");
            finishReturn();
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_return:
                finishReturn();
                break;
            case R.id.linrar_wifi_ssid:
                wifiStartScan();
                break;
            case R.id.img_wifi_password:
                setEditTextDrawableRight((ImageView) view, textWifiPassword, !isShowPwdEditText(textWifiPassword));
                break;
            case R.id.btn_start_configure:     //开始配网
                if(accountID!=null && accountID.length()>0) {
                    textTouchState.setText("");
                    espTouchManage.set(
                            textWifiSSID.getText().toString(),
                            textWifiBSSID.getText().toString(),
                            textWifiPassword.getText().toString());
                    if(switchBind.isChecked()) {
                        espTouchManage.startProvisioning(accountID, textDevName.getText().toString());
                    }else{
                        espTouchManage.startProvisioning(1,null,EspTouchManage.DEFAULT_AES_KEY);
                    }
                    espTouchManage.setProvisioningListener(provisioningListener);
                }
                break;
        }
    }

    @Override
    protected void onMessageArrived(MqttMag message) {
        super.onMessageArrived(message);
        CmdDataPacket cmdDataPacket = CmdDataPacket.fromBytes(message.getMessage());  //将消息转为标准命令结构
        if(cmdDataPacket!=null) {
            if(cmdDataPacket.command==CmdDataPacket.CMD_SC_SEND_FINISH) {
                String bssid = message.getTopic().replace(base_topic, "");  //去掉基主题部分
                bssid = BasicsUtil.addMacColon(bssid);

                StringBuffer sb = new StringBuffer(textTouchState.getText());
                //这里返回配置成功的结果
                sb.append(String.format(getString(R.string.smart_config_success), bssid));
                if (switchBind.isChecked()) {        //只有当配置绑定时才插入数据
                    insertData(bssid, textDevName.getText().toString());    //插入数据
                    resultData = new Intent();
                    resultData.putExtra(Constants.KEY_MAC_ID, bssid);
                    resultData.putExtra(Constants.KEY_DEV_NAME, textDevName.getText().toString());
                }
                textTouchState.setText(sb);
                espTouchManage.release();
                btnConfigure.setEnabled(true);
                finishReturn();
            }
        }
    }
    /**
     * 开始扫描WiFi
     */
    private void wifiStartScan(){
        //注册扫描结果监听器
        wifiTools.setScanListener(wifiList -> {
            if(wifiList!=null) {
                showPopupWiFiList((View) textWifiSSID.getParent().getParent(), wifiList);
//                if(popupMenu!=null){
//                    popupMenu.show();
//                }
            }
        });
        wifiTools.startScan(0);          //开始扫描
    }
    /**********************组文本输入框内容改变侦听器**************************/
    private TextWatcher devNameChangedListener=new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // 文本改变时的回调
            if(TextUtils.isEmpty(s)){
                textDenNameCount.setText("0/25");
            }else {
                int groupCount= s.toString().getBytes(EspTouchManage.GB2312).length ;
                textDenNameCount.setText(String.format("%d/25", groupCount));
                if(groupCount==0){
                    textDenNameCount.setTextColor(getColor(android.R.color.darker_gray));
                }else if(groupCount>0 && groupCount<=25){
                    textDenNameCount.setTextColor(getColor(android.R.color.holo_green_light));
                    textDevName.setTextColor(getColor(android.R.color.black));
                }else{
                    textDenNameCount.setTextColor(getColor(android.R.color.holo_red_light));
                    textDevName.setTextColor(getColor(android.R.color.holo_red_light));
                }
            }
        }
        @Override
        public void afterTextChanged(Editable editable) {

        }
    };
    /**********************智能配网配置侦听器*********************************/
    EspTouchManage.OnProvisioningListener provisioningListener = new EspTouchManage.OnProvisioningListener() {
        @Override
        public void onStart() {
            textTouchState.setText(R.string.smart_config_start);
            btnConfigure.setEnabled(false);
        }
        @Override
        public void onSuccess(List<EspTouchManage.ProvisioningResult> results) {
            StringBuffer sb = new StringBuffer(textTouchState.getText());
            //这里返回配置成功的结果
            for(EspTouchManage.ProvisioningResult result:results){
                sb.append(String.format(getString(R.string.smart_config_success), result.bssid));
                if(switchBind.isChecked()) {        //只有当配置绑定时才插入数据
                    insertData(result.bssid, textDevName.getText().toString());    //插入数据
                    resultData=new Intent();
                    resultData.putExtra(Constants.KEY_MAC_ID, result.bssid);
                    resultData.putExtra(Constants.KEY_DEV_NAME, textDevName.getText().toString());
                }
            }
            textTouchState.setText(sb);
        }
        @Override
        public void onFailure(Exception e) {
            StringBuffer sb = new StringBuffer(textTouchState.getText());
            sb.append("\n");
            sb.append(getString(R.string.smart_config_fail));
            textTouchState.setText(sb);
            espTouchManage.release();
            btnConfigure.setEnabled(true);
        }
        @Override
        public void onStop() {
            //linearTouchState.setVisibility(View.GONE);
            StringBuffer sb = new StringBuffer(textTouchState.getText());
            sb.append("\n");
            sb.append(getString(R.string.smart_config_stop));
            textTouchState.setText(sb);
            espTouchManage.release();
            btnConfigure.setEnabled(true);
            finishReturn();
        }
    };
    /**完成返回上一个活动*/
    private void finishReturn(){
        if(resultData!=null){
            this.setResult(RESULT_CODE+1);
        }
        finish();
    }
    /**
     * 编辑框密码可见
     * @param editText 编辑框
     * @return
     */
    private boolean isShowPwdEditText(EditText editText) {
        int inputType = editText.getInputType();
        if (inputType == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)) {
            return false;
        } else {
            return true;
        }
    }
    /**
     * 设置编辑框左边图标及密码显示状态
     * @param view 单击的视图
     * @param editText 编辑框对象
     * @param isShowPwd 显示密码
     */
    private void setEditTextDrawableRight(ImageView view, EditText editText, boolean isShowPwd) {
        int password_Type = isShowPwd ? EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : EditorInfo.TYPE_TEXT_VARIATION_PASSWORD;
        if (view != null) {
            view.setImageResource(isShowPwd ? R.drawable.ic_pwd_show_24dp : R.drawable.ic_pwd_hide_24dp);
        }
        editText.setInputType(EditorInfo.TYPE_CLASS_TEXT | password_Type);
        editText.setSelection(editText.getText().length());
    }
    /**
     * 显示弹窗扫描的WiFi下拉列表
     * @param anchor 瞄定视图
     * @param wifiList 可用wifi列表
     */
    private void showPopupWiFiList(View anchor, List<WiFiTools.WiFi> wifiList){
        WiFiAdapter adapter = new WiFiAdapter(this,wifiList);
        ListPopupWindow popupWindow = new ListPopupWindow(this);
        popupWindow.setAnchorView(anchor);//设置ListPopupWindow的锚点，关联mButton位置
        popupWindow.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT); //设置宽度
        popupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setModal(true);
        popupWindow.setAdapter(adapter);
        popupWindow.setOnItemClickListener((parent, view, position, id)->{
            WiFiTools.WiFi menuItem = wifiList.get(position);
            textWifiSSID.setText(menuItem.ssid);
            textWifiBSSID.setText(menuItem.bssid.toUpperCase());
            popupWindow.dismiss();
            wifiTools.stopScan();    //下拉列表关闭时停止wifi扫描
        });
        popupWindow.show();
    }
    /**
     * 将数据插入到数据库表单
     * @param devId 设备ID
     * @param devName 设备名称（如果为空，名称将使用组ID）
     */
    private void insertData( String devId,String devName){
        if(devId!=null) {
            ContentValues gValues = new ContentValues();
            gValues.put(Constants.KEY_MAC_ID, devId);
            gValues.put(Constants.KEY_ACCOUNT_ID, accountID);
            if (devName == null || devName.length() == 0) {
                gValues.put(Constants.KEY_DEV_NAME, devId);
            } else {
                gValues.put(Constants.KEY_DEV_NAME, devName);
            }
            // 使用CONFLICT_REPLACE策略执行插入操作，如果bssid已存在，则更新该记录
            long result = DatabaseManager.insertWithOnConflict(Constants.TABLE_DEV,  gValues, SQLiteDatabase.CONFLICT_REPLACE);
            if (result != -1) {
                Log.d("Database Operation", "DeviceId: " + devId + " processed successfully.");
                if (DatabaseManager.getDatabaseVersion() >= 14) {
                    // API 14及以上，直接通过返回值判断是否为插入或更新
                    Log.d("Database Operation", "Record was " + (result == 1 ? "inserted" : "updated"));
                } else {
                    // 对于早期版本，此处可根据需要添加额外的逻辑来确定是插入还是更新
                    Log.d("Database Operation", "Record inserted or updated based on conflict resolution strategy.");
                }
            } else {
                Log.e("Database Operation", "Failed to process Bssid: " + devId);
            }
        }
    }
}